package flc.ast.activity;

import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.blankj.utilcode.util.VolumeUtils;
import com.hpplay.sdk.source.api.LelinkPlayerInfo;
import com.hpplay.sdk.source.api.LelinkSourceSDK;
import com.stark.cast.screen.CastScreenManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityProAudioBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import stark.common.basic.media.bean.AudioBean;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.utils.UriUtil;

public class ProAudioActivity extends BaseAc<ActivityProAudioBinding> {

    public static String audioPath;
    private CastScreenManager mCastScreenManager;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private long audioLength;


    @Override
    protected int onCreate() {
        return R.layout.activity_pro_audio;
    }

    @Override
    protected void initView() {
        mDataBinding.ivProAudioBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivSelAudio.setOnClickListener(this);
        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.tvRetrogress.setOnClickListener(this);
        mDataBinding.tvFastForward.setOnClickListener(this);
        mDataBinding.ivVolumeAdd.setOnClickListener(this);
        mDataBinding.ivVolumeReduce.setOnClickListener(this);

        mCastScreenManager = CastScreenManager.getInstance();
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.ivSelAudio) {//选择视频
            Intent intent = new Intent(this, SelAudioActivity.class);
            intent.putExtra(Content.Again, "Again");
            startActivityForResult(intent, Content.PRO_SEL);
        }
        if (id == R.id.ivPlay) {//播放/暂停
            if (mediaPlayer.isPlaying()) {
                mDataBinding.ivPlay.setImageResource(R.drawable.azt);
                mediaPlayer.pause();
            } else {
                mDataBinding.ivPlay.setImageResource(R.drawable.abf);
                mediaPlayer.start();
            }
        } else if (id == R.id.tvRetrogress) {//倒退10s
            // 获取当前播放位置（毫秒）
            int currentPos = mediaPlayer.getCurrentPosition();
            // 倒退10秒（10000毫秒）并确保不小于0
            int newPos = Math.max(0, currentPos - 10000);
            mediaPlayer.seekTo(newPos);
        } else if (id == R.id.tvFastForward) {//快进10s
            // 获取当前播放位置（毫秒）
            int currentPos = mediaPlayer.getCurrentPosition();
            // 倒退10秒（10000毫秒）并确保大小于时长
            int newPos = (int) Math.max(audioLength, currentPos + 10000);
            mediaPlayer.seekTo(newPos);
        } else if (id == R.id.ivVolumeAdd) {//音量+
            int volume = VolumeUtils.getVolume(AudioManager.STREAM_MUSIC);
            int max = VolumeUtils.getMaxVolume(AudioManager.STREAM_MUSIC);
            if (volume < max) {
                VolumeUtils.setVolume(AudioManager.STREAM_MUSIC, volume + 1, 0);
            }
        } else if (id == R.id.ivVolumeReduce) {//音量-
            int volume = VolumeUtils.getVolume(AudioManager.STREAM_MUSIC);
            int min = VolumeUtils.getMinVolume(AudioManager.STREAM_MUSIC);
            if (volume > min) {
                VolumeUtils.setVolume(AudioManager.STREAM_MUSIC, volume - 1, 0);
            }
        }
    }

    @Override
    protected void initData() {
        try {
            setMedia();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        proMusic();
        saveRecord();
    }

    //音乐投屏
    private void proMusic() {
        LelinkPlayerInfo playerInfo = new LelinkPlayerInfo();
        playerInfo.setType(LelinkSourceSDK.MEDIA_TYPE_AUDIO);
        Uri uri = Uri.parse(audioPath);
        if (UriUtil.isContentSchemeUri(uri)) {
            playerInfo.setLocalUri(uri);
        } else {
            playerInfo.setLocalPath(audioPath);
        }
        mCastScreenManager.startPlay(playerInfo);
    }

    private void setMedia() throws IOException {
        mediaPlayer = new MediaPlayer();
        audioLength = MediaUtil.getDuration(audioPath);
        //设置seekbar
        mediaPlayer.setDataSource(audioPath);
        mediaPlayer.prepare();
        mediaPlayer.seekTo(1);
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.ivPlay.setImageResource(R.drawable.azt);
                mp.seekTo(1);
            }
        });
        //直接播放音频
        mediaPlayer.start();
        mDataBinding.ivPlay.setImageResource(R.drawable.abf);
    }

    private void saveRecord() {
        List<String> listSave = new ArrayList<>();
        listSave.add(audioPath);
        List<String> listSp = AppSpUtils.getAudioList();
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            AppSpUtils.saveAudioList(listSp);
        } else {
            AppSpUtils.saveAudioList(listSave);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String path = data.getStringExtra(Content.selPath);
            if (requestCode == Content.PRO_SEL) {
                audioPath = path;
                proMusic();
                mediaPlayer.release();
                try {
                    setMedia();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }

}